import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { removeToken } from '@/utils/auth';

// 用户信息类型定义
export interface User {
  id: string;
  username: string;
  role: 'admin' | 'user';
  avatar?: string;
  permissions: string[];
}

// 认证状态类型
interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
}

// 初始状态
const initialState: AuthState = {
  user: null,
  isAuthenticated: false,
  loading: false,
  error: null
};

// 创建认证Slice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 登录开始
    loginStart: (state) => {
      state.loading = true;
      state.error = null;
    },
    // 登录成功
    loginSuccess: (state, action: PayloadAction<User>) => {
      state.loading = false;
      state.isAuthenticated = true;
      state.user = action.payload;
      state.error = null;
    },
    // 登录失败
    loginFailure: (state, action: PayloadAction<string>) => {
      state.loading = false;
      state.isAuthenticated = false;
      state.user = null;
      state.error = action.payload;
    },
    // 登出
    logout: (state) => {
      state.user = null;
      state.isAuthenticated = false;
      removeToken(); // 清除本地存储的Token
    },
    // 清除错误
    clearError: (state) => {
      state.error = null;
    }
  }
});

// 导出actions
export const { loginStart, loginSuccess, loginFailure, logout, clearError } = authSlice.actions;

// 导出reducer
export default authSlice.reducer;
